package com.ibm.moa.outmail.utils;

import java.security.MessageDigest;

public class MD5Encryptor {

	public static byte[] encrypt(byte[] content) {
		byte[] result = null;
		try {
			MessageDigest md5 = MessageDigest.getInstance("md5");
			md5.update(content);
			result = md5.digest();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}

	public static String encrypt(String content) {
		String result = null;
		try {
			byte[] data = content.getBytes("UTF-8");
			result = byte2Hex(encrypt(data));
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}

	public static String encrypt(String content, String charsetName) {
		String result = null;
		try {
			byte[] data = content.getBytes(charsetName);
			result = byte2Hex(encrypt(data));
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}

	/**
	 * 将字符窜转化为byte数组
	 * 
	 * @param hex
	 * @return
	 */
	public static byte[] hex2Byte(String in) {
		if (in == null) {
			return null;
		}
		int len = in.length();
		byte[] ret = new byte[len / 2];
		for (int i = 0; i < len; i += 2) {
			ret[i / 2] = Integer.decode("0x" + in.substring(i, i + 2)).byteValue();
		}
		return ret;
	}

	/**
	 * 将byte数组转为16进制字符串
	 * 
	 * @param b
	 * @return
	 */
	public static String byte2Hex(byte[] b) {
		if (b == null) {
			return null;
		}
		String stmp = "";
		StringBuffer sb = new StringBuffer();
		for (int n = 0; n < b.length; n++) {
			stmp = Integer.toHexString(b[n] & 0XFF);
			if (stmp.length() == 1) {
				sb.append("0");
			}
			sb.append(stmp);
		}
		return sb.toString();
	}
}
